package com.icode.bq;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2020-12-12 17:57
 */
public class BlockingQueueTest {

    public static void main(String[] args) {
        try {
            test4();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * add()添加元素会抛出异常
     */
    public static void test1(){
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);

        queue.add(1);
        queue.add(2);
        queue.add(3);
        //java.lang.IllegalStateException: Queue full
        //queue.add(4);
        System.out.println(queue.element());//获取队首元素
        System.out.println("-----------");

        System.out.println(queue.remove());
        System.out.println(queue.remove());
        System.out.println(queue.remove());

        //java.util.NoSuchElementException
        queue.remove();
    }
    /**
     * offer()添加元素不会抛出异常。而且方法添加了ReentrantLock
     */
    public static void test2(){
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);

        System.out.println(queue.offer(1)); //true
        System.out.println(queue.offer(2)); //true
        System.out.println(queue.offer(3)); //true
        System.out.println(queue.offer(4)); //false
        System.out.println(queue.toString());
        System.out.println("-----------");
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll()); //null
    }
    /**
     *  等待 ，阻塞（一直等待）
     */
    public static void test3() throws InterruptedException {
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);

        queue.put(1);
        queue.put(2);
        queue.put(3);
        //System.out.println("进入阻塞状态");
        //queue.put(4);
        System.out.println("...");
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());//进入阻塞状态
    }

    /**
     *  等待 ，阻塞（超时等待）
     */
    public static void test4() throws InterruptedException {
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);

        System.out.println(queue.offer(1)); //true
        System.out.println(queue.offer(2)); //true
        System.out.println(queue.offer(3)); //true
        System.out.println("进入阻塞状态");
        System.out.println(queue.offer(4,2, TimeUnit.SECONDS));
        System.out.println("跳出阻塞状态");
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println("进入阻塞状态");
        System.out.println(queue.poll(2,TimeUnit.SECONDS));
        System.out.println("跳出阻塞状态");


    }
}
